package com.mallcloud.mall.auth.handler;

import com.mallcloud.mall.common.security.service.MallUser;
import com.mallcloud.mall.admin.api.dto.SysLogDTO;
import com.mallcloud.mall.admin.api.feign.RemoteLogService;
import com.mallcloud.mall.common.core.constant.CommonConstants;
import com.mallcloud.mall.common.log.util.SysLogUtils;
import com.mallcloud.mall.common.security.handler.AuthenticationLogoutHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 退出事件处理
 */
@Slf4j
@Component
@AllArgsConstructor
public class MallAuthenticationLogoutEventHandler implements AuthenticationLogoutHandler {

	private final RemoteLogService logService;

	/**
	 * 处理登录成功方法
	 * <p>
	 * 获取到登录的authentication 对象
	 * @param authentication 登录对象
	 * @param request 请求
	 * @param response 返回
	 */
	@Async
	@Override
	public void handle(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
		MallUser mallUser = (MallUser) authentication.getPrincipal();

		SysLogDTO sysLog = SysLogUtils.getSysLog(request, mallUser.getUsername());
		sysLog.setTitle(mallUser.getUsername() + "用户退出登录");
		sysLog.setParams(mallUser.getUsername());
		Object startTimeStr = request.getAttribute(CommonConstants.REQUEST_START_TIME);
		if (Objects.nonNull(startTimeStr)) {
			Long startTime = Long.parseLong((String) startTimeStr);
			Long endTime = System.currentTimeMillis();
			sysLog.setTime(endTime - startTime);
		}

		// 获取clientId 信息
		OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
		sysLog.setServiceId(auth2Authentication.getOAuth2Request().getClientId());
		sysLog.setTenantId(mallUser.getTenantId());
		// 保存退出的token
		String token = request.getHeader(HttpHeaders.AUTHORIZATION);
		sysLog.setParams(token);

//		logService.saveLog(sysLog, SecurityConstants.FROM_IN);
		log.info("用户：{} 退出成功, token:{}  已注销", mallUser.getUsername(), token);
	}

}
